const { baseUrl } = require("./index");
const store = require('../storage')
const request = require("miniapp-request");

var login = function () {
    return new Promise(function (resolve, reject) {
        const infos = store.get();
        let openid = infos.openid;
        // if (openid && openid.length > 5) {
        //     console.log("===============login：已有openid，不在调用wx.login");
        //     // 已有openid，不在调用wx.login
        //     resolve(infos);
        //     return;
        // }
        console.log("===============login：调用wx.login前");
        wx.login({
            success: function (res) {
                // console.log("===============wx.login：success");
                // console.log(res);
                wx.request({
                    header: {
                        "Content-Type": "application/json"
                    },
                    url: baseUrl + "/Index/user/toLogin.html",
                    data: {
                        code: res.code
                    },
                    success: function (res) {
                        var rt = res.data;
                        if (rt.code == 0) {
                            const { info } = rt;

                            //存在本地的baseurl
                            const storageBaseurl = infos.baseUrl;
                            //接口返回的baseurl
                            const callbackBaseurl = info.baseUrl;

                            if (callbackBaseurl && storageBaseurl !== callbackBaseurl) {
                                request.defaults.baseUrl = callbackBaseurl;
                            }

                            openid = info.openid;
                            store.set(info);
                            store.set(info.status, 'user_status');

                            resolve(info);
                        } else {
                            wx.showToast({
                                title: '请刷新页面重试',
                                duration: 5000,
                                icon: 'none'
                            })
                            reject(res);
                        }
                    },
                    fail(e) {
                        console.log("===============wx.login wx.request：fail");
                        console.log(e);
                        wx.showToast({
                            title: '网络异常，toLogin失败!',
                            duration: 5000,
                            icon: 'none'
                        })
                        reject(e);
                    }
                });
            },
            fail(e) {
                console.log("===============wx.login：fail");
                console.log(e);
                wx.showToast({
                    title: '微信登录异常，请稍后再试!',
                    duration: 5000,
                    icon: 'none'
                })
                reject(e);
            }
        });
    });
};

global.loginPromise = login()

module.exports = login;